package com.woniuxy.trade.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.common.model.dto.bank.BaseResult;
import com.woniuxy.common.model.dto.trade.BorrowRecordDTO;
import com.woniuxy.common.model.vo.trade.BorrowRecordVo;
import com.woniuxy.common.model.vo.trade.BorrowSyncRecordVo;
import com.woniuxy.common.model.vo.user.UserInfoVo;
import com.woniuxy.common.result.Result;
import com.woniuxy.common.utils.TokenUtils;
import com.woniuxy.sddfp.api.bank.TradeLogApi;
import com.woniuxy.sddfp.api.user.UserApi;
import com.woniuxy.trade.entity.BorrowRecord;
import com.woniuxy.trade.mapper.BorrowRecordMapper;
import com.woniuxy.trade.service.IBorrowRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yellow Docter
 * @date 2023 -07-31
 * @desc    Primary可以理解为默认优先选择, 同时不可以同时设置多个,
 *          内部实质是设置BeanDefinition的primary属性
 */
@Slf4j
@Service
public class IBorrowRecordServiceImpl extends ServiceImpl<BorrowRecordMapper, BorrowRecord> implements IBorrowRecordService {

    @Autowired
    private UserApi userApi;

    @Autowired
    private TradeLogApi tradeLogApi;

    @Override
    public void borrow(BorrowRecordDTO borrowRecordDTO) {
        //01 组装
        BorrowRecord borrowRecord = new BorrowRecord();

        //需要用到userId
        String userId = TokenUtils.getUserId();

        Result<UserInfoVo> result = userApi.findById(Long.parseLong(userId));
        UserInfoVo userInfoVo = result.getData();
        //2个在用户userInfo中
        borrowRecord.setUserId(Long.parseLong(userId));
        borrowRecord.setUserCode(userInfoVo.getUserCode());
        borrowRecord.setName(getCreateName(userInfoVo));

        //给指定要求的数据就可以
        // 设置借款编号，	"BO_"
        borrowRecord.setBorrowRecordNo("BO_" + UUID.randomUUID().toString().substring(0,10));
        // 设置用户id
        borrowRecord.setUserId(Long.parseLong(userId));

        // 设置借款期限、借款金额
        borrowRecord.setPeriod(borrowRecordDTO.getPeriod());
        borrowRecord.setAmount(borrowRecordDTO.getAmount());
        borrowRecord.setType("BORROW");

        // 各种利率 （先写死，应该放到配置文件中）
        borrowRecord.setInvestRate(new BigDecimal("10")); //投资年化利率
        borrowRecord.setBorrowerRate(new BigDecimal("10")); //借款年化利率
        borrowRecord.setCommissionRate(new BigDecimal("10")); //平台佣金年化利率
        // 还款方式：等额本金（DEBJ）、等额本息（DEBX）
        // "DEBX", "等额本息" /"DEBJ", "等额本金"  /"ALL", 一次性还款（含本息）  / "XXHB", "先息后本"
        borrowRecord.setRepaymentWay("DEBX");
        // 借款状态：新建
        borrowRecord.setBorrowStatus("NEW");

        borrowRecord.setCreateDate(new Date());  //创建时间
        borrowRecord.setModifyDate(new Date());  //修改时间
        borrowRecord.setStatus(false);           //不可用
        borrowRecord.setDescription("无");

        //02 保存
        save(borrowRecord);

    }

    @Override
    public String changeStatus(Long borrowId, Integer status) {

        //业务逻辑
        //01 查询 借款记录
        BorrowRecord borrowRecord = getOne(Wrappers.lambdaQuery(BorrowRecord.class).eq(BorrowRecord::getId, borrowId));
        //02 组装数据  发送到托管服务
        BorrowSyncRecordVo borrowSyncRecordVo = BeanUtil.copyProperties(borrowRecord,BorrowSyncRecordVo.class);
        System.out.println("远程调用调用发送到托管服务...");
        Result<BaseResult> result = tradeLogApi.syncBorrowRecord(borrowSyncRecordVo);
        //03 托管服务 返回数据 更新 借款记录 （状态）
        BaseResult data = result.getData();
        if ( data != null && data.getRespMsg().equals("成功")) {
            //进行更新
            //根据远程调用结果，返回msg=成功，修改BorrowRecord表的status=1、borrow_status为SYNC
            update(
                    Wrappers.lambdaUpdate(BorrowRecord.class)
                            .set(BorrowRecord::getBorrowStatus,"SYNC")
                            .set(BorrowRecord::getStatus,status)
                            .set(BorrowRecord::getModifyDate,new Date())
                            .eq(BorrowRecord::getId,borrowId)
            );
            return "借款记录审核通过..";
        }
        return "借款记录审核异常.....";
    }

    /**
     * 用户接口的name
     * @param userInfoVo
     * @return
     */
    private String getCreateName(UserInfoVo userInfoVo) {
//        String name = "张三女士第一次借款";
        String name =  userInfoVo.getUserName();

        //性别判断 通过身份证号码判断
        String identityCode = userInfoVo.getIdentityCode();
        String idNum = identityCode.substring(16, 17);
        String sex = Integer.parseInt(idNum) % 2 == 0 ? "女士" :"男士";

        //借款条件查询
        LambdaQueryWrapper<BorrowRecord> borrowRecordLambdaQueryWrapper = Wrappers.lambdaQuery(BorrowRecord.class).eq(BorrowRecord::getUserCode, userInfoVo.getUserCode());
        String count = "第" + (count(borrowRecordLambdaQueryWrapper) + 1) + "次借款";

        return name + sex + count;

    }
}
